export interface MessagePart {
  type: "text" | "code";
  content: string;
  language?: string;
}

// 把 AI 输出拆成文本 + 代码块
export const processAssistantMessage = (content: string): MessagePart[] => {
  const parts: MessagePart[] = [];
  const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
  const incompleteCodeBlockRegex = /```(\w+)?\n([\s\S]*?)(?=\n```|$)/g;

  let lastIndex = 0;
  let match;

  // 先处理完整的代码块
  while ((match = codeBlockRegex.exec(content)) !== null) {
    // 前面的纯文本
    if (match.index > lastIndex) {
      parts.push({
        type: "text",
        content: content.slice(lastIndex, match.index),
      });
    }
    // 代码块
    parts.push({
      type: "code",
      language: match[1] || "text",
      content: match[2],
    });

    lastIndex = codeBlockRegex.lastIndex;
  }

  // 处理未闭合的代码块（流式响应时可能发生）
  const remainingContent = content.slice(lastIndex);
  const incompleteMatch = incompleteCodeBlockRegex.exec(remainingContent);
  if (incompleteMatch && incompleteMatch[2]) {
    // 前面的纯文本
    if (incompleteMatch.index > 0) {
      parts.push({
        type: "text",
        content: remainingContent.slice(0, incompleteMatch.index),
      });
    }
    // 不完整的代码块
    parts.push({
      type: "code",
      language: incompleteMatch[1] || "text",
      content: incompleteMatch[2],
    });
    lastIndex = lastIndex + incompleteCodeBlockRegex.lastIndex;
  }

  // 最后剩余的文本
  if (lastIndex < content.length) {
    parts.push({
      type: "text",
      content: content.slice(lastIndex),
    });
  }

  return parts;
};
